<?php
//切换标签插件
class cy_tab extends WP_Widget {

    function cy_tab() {
        $widget_ops = array('description' => '标签切换的小工具，显示最热文章、最新文章、随机文章');
        $this->WP_Widget('cy_tab', '草野插件：切换标签', $widget_ops);
    }

    function form($instance) {
        $days = isset($instance['days']) ? absint($instance['days']) : 90;
        $posts_num = isset($instance['posts_num']) ? absint($instance['posts_num']) : 10;
?>
    <p><label for="<?php echo $this->get_field_id('days'); ?>"><?php _e('统计天数：'); ?></label>
        <input id="<?php echo $this->get_field_id('days'); ?>" name="<?php echo $this->get_field_name('days'); ?>" type="text" value="<?php echo $days; ?>" size="3" /></p>
    <p><label for="<?php echo $this->get_field_id('posts_num'); ?>"><?php _e('文章数量：'); ?></label>
        <input id="<?php echo $this->get_field_id('posts_num'); ?>" name="<?php echo $this->get_field_name('posts_num'); ?>" type="text" value="<?php echo $posts_num; ?>" size="3" /></p>
<?php
    }

    function update($new_instance, $old_instance) {
        return $new_instance;
    }

    function widget($args, $instance) {
        extract( $args );
        $posts_num = absint($instance['posts_num']);
        $days = absint($instance['days']);
        echo $before_widget;
        echo cy_widget_tab($posts_num,$days);
        echo $after_widget;
    }
}
register_widget('cy_tab');

function cy_widget_tab($posts_num,$days){
?>
<div class="tab_box" id="tab_box_posts">
<ul class="tab_menu btn">
<li class="current">热门文章</li><li>最新发布</li><li>随机推荐</li>
</ul>
<div class="tab_content" style="clear:both;">
<ul class="tab_post_links">
<?php 
global $wpdb;
$sql = "SELECT ID , post_title , comment_count FROM $wpdb->posts WHERE post_type = 'post' AND TO_DAYS(now()) - TO_DAYS(post_date) < $days AND ($wpdb->posts.`post_status` = 'publish' OR $wpdb->posts.`post_status` = 'inherit') ORDER BY comment_count DESC LIMIT 0 , $posts_num ";
$posts = $wpdb->get_results($sql);
foreach($posts as $post) :?>
<li><a href="<?php echo get_permalink( $post->ID ); ?>" rel="external" title="<?php echo $post->post_title; ?> (<?php echo $post->comment_count; ?>条评论)"><?php echo $post->post_title; ?></a></li>
<?php endforeach; ?>
</ul>
<ul class="tab_post_links hide"><?php $myposts = get_posts("numberposts=$posts_num&offset=0");foreach($myposts as $post) :?>
<li><a href="<?php echo get_permalink( $post->ID ); ?>" rel="external" title="<?php echo $post->post_title; ?>"><?php echo $post->post_title; ?></a></li>
<?php endforeach; ?>
</ul>
<ul class="tab_post_links hide"><?php $myposts = get_posts("numberposts=$posts_num&orderby=rand");foreach($myposts as $post) :?>
<li><a href="<?php echo get_permalink( $post->ID ); ?>" rel="external" title="<?php echo $post->post_title; ?>"><?php echo $post->post_title; ?></a></li>
<?php endforeach; ?>
</ul>
</div>
</div>
<?php
}
?>